import { isArray } from '@/utils/validate/data.js';

export const getDifferenceKeyFromTwoObject = (obj1, obj2) => {
	let resultObj = {},
		isDifference = false;
	Object.keys(obj1).forEach(key => {
		if (obj1[key] !== obj2[key]) {
			resultObj[key] = obj1[key];
			isDifference = true;
		}
	});
	return {
		isDifference,
		result: resultObj,
	};
};

// 判断参数是否是其中之一
export function oneOf(value, validList) {
	for (let i = 0; i < validList.length; i++) {
		if (value === validList[i]) {
			return true;
		}
	}
	return false;
}

//深拷贝
export const deepcopy = function(source) {
	if (!source) {
		return source;
	}
	let sourceCopy = source instanceof Array ? [] : {};
	for (let item in source) {
		sourceCopy[item] = typeof source[item] === 'object' ? deepcopy(source[item]) : source[item];
	}
	return sourceCopy;
};

/**
 * 对象或者数组的深copy
 * @param {*} obj
 */
export const cloneObj = function(obj) {
	var str,
		newobj = obj.constructor === Array ? [] : {};
	if (typeof obj !== 'object') {
		return;
	} else if (window.JSON) {
		(str = JSON.stringify(obj)), //系列化对象
			(newobj = JSON.parse(str)); //还原
	} else {
		for (var i in obj) {
			newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
		}
	}
	return newobj;
};

export const mergeObject = (src, target) => {
	let obj = { ...src };
	Object.keys(obj).forEach(key => {
		if (target[key] !== undefined || target[key] !== null) {
			obj[key] = target[key];
		}
	});
	return obj;
};

export const difference = (target, source) => {
	let newObj = {};
	Object.keys(source).forEach(item => {
		if (source[item] != target[item]) {
			newObj[item] = target[item];
		}
	});
	return newObj;
};

export const forEach = (obj, fn) => {
	// Don't bother if no value provided
	if (obj === null || typeof obj === 'undefined') {
		return;
	}

	// Force an array if not already something iterable
	if (typeof obj !== 'object') {
		/*eslint no-param-reassign:0*/
		obj = [obj];
	}

	if (isArray(obj)) {
		// Iterate over array values
		for (var i = 0, l = obj.length; i < l; i++) {
			fn.call(null, obj[i], i, obj);
		}
	} else {
		// Iterate over object keys
		for (var key in obj) {
			if (Object.prototype.hasOwnProperty.call(obj, key)) {
				fn.call(null, obj[key], key, obj);
			}
		}
	}
};
